var express = require('express');
var router = express.Router();
var multer = require('multer');
var models = require('../models');
var moment = require('moment');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/images/');
    },
    filename: function (req, file, cb) {
        let filetype = file.originalname.substring(file.originalname.lastIndexOf(".")), date=new Date();
        cb(null, moment().format('YYYYMMDD')+ Math.random().toString().substr(2, 10) + filetype);
    }
});
var upload = multer({storage: storage});

router.post('/upload', upload.single('file'), function (req, res, next) {
    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
        new_image = {
            path: '/images/' + req.file.filename,
            owner_unique: req.body.userunique,
            owner_name: req.body.username,
            ip: ip,
            filesize: req.file.size,
            filename: req.file.originalname
        };

    models.images.create(new_image).then(function (cimg) {
        res.send({
            code: 200,
            message: 'success',
            path: cimg.path
        });
    });
});

router.post('/upload/array',upload.array('file',10),function (req,res,next) {
    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
        new_image = {
            path: '',
            owner_unique: req.body.userunique,
            owner_name: req.body.username,
            ip: ip,
            filesize: 0,
            filename: ''
        },
        paths =[];
    req.files.forEach(function (file) {
       new_image.path='/images/' + file.filename;
       new_image.filesize = file.size;
       new_image.filename =file.originalname;
       paths.push(new_image.path);
       models.images.create(new_image);
    });

    res.send({
        code:200,
        message:'success',
        paths:paths
    });

});



module.exports = router;
